package com.haixiaoke.saas.house.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.haixiaoke.saas.bill.service.IBillService;
import com.haixiaoke.saas.common.constant.HouseConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.house.domain.House;
import com.haixiaoke.saas.house.domain.HouseFacilities;
import com.haixiaoke.saas.house.domain.HouseLabel;
import com.haixiaoke.saas.house.mapper.HouseMapper;
import com.haixiaoke.saas.house.service.IHouseFacilitiesService;
import com.haixiaoke.saas.house.service.IHouseLabelService;
import com.haixiaoke.saas.house.service.IHouseLeadService;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.house.vo.HomePageVO;
import com.haixiaoke.saas.lock.service.IDeviceLockService;
import com.haixiaoke.saas.lock.service.impl.LockDevicesService;
import com.haixiaoke.saas.repairs.service.IRepairsService;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 房屋Service业务层处理
 *
 * @author panda
 * @date 2025-06-26
 */
@Service
public class HouseServiceImpl implements IHouseService {
    @Autowired
    private HouseMapper houseMapper;
    @Autowired
    private IHouseLabelService houseLabelService;
    @Autowired
    private IHouseFacilitiesService houseFacilitiesService;
    @Autowired
    private IBillService billService;
    @Autowired
    private IRepairsService repairsService;
    @Autowired
    private IHouseLeadService houseLeadService;
    @Autowired
    private IDeviceLockService deviceLockService;
    @Autowired
    private LockDevicesService lockDevicesService;

    /**
     * 查询房屋
     *
     * @param houseId 房屋主键
     * @return 房屋
     */
    @Override
    public House selectHouseByHouseId(String houseId) {
        return houseMapper.selectHouseByHouseId(houseId);
    }

    /**
     * 查询房屋列表
     *
     * @param house 房屋
     * @return 房屋
     */
    @Override
    public List<House> selectHouseList(House house) {
        return houseMapper.selectHouseList(house);
    }

    /**
     * 新增房屋
     *
     * @param house 房屋
     * @return 结果
     */
    @Override
    public AjaxResult insertHouse(House house) {
        AjaxResult ajaxResult = this.checkParams(house);
        if (ajaxResult != null) {
            return ajaxResult;
        }
        String houseId = "H" + System.currentTimeMillis() + RandomUtils.nextInt(10000, 100000);
        house.setHouseId(houseId);
        house.setHousePicture(StringUtils.join(house.getHousePictureList(), ","));
        house.setCreateTime(DateUtils.getNowDate());
        int result = houseMapper.insertHouse(house);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改房屋
     *
     * @param house 房屋
     * @return 结果
     */
    @Override
    public AjaxResult updateHouse(House house) {
        AjaxResult ajaxResult = this.checkParams(house);
        if (ajaxResult != null) {
            return ajaxResult;
        }
        House houseByHouseId = houseMapper.selectHouseByHouseId(house.getHouseId());
        if (!StrUtil.equals(houseByHouseId.getTenantId(), house.getTenantId())) {
            return AjaxResult.error("不能操作其他机构的房屋");
        }
        house.setHousePicture(StringUtils.join(house.getHousePictureList(), ","));
        house.setUpdateTime(DateUtils.getNowDate());
        int result = houseMapper.updateHouse(house);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 批量删除房屋
     *
     * @param houseIds 需要删除的房屋主键
     * @return 结果
     */
    @Override
    public int deleteHouseByHouseIds(String[] houseIds) {
        return houseMapper.deleteHouseByHouseIds(houseIds);
    }

    /**
     * 删除房屋信息
     *
     * @param houseId 房屋主键
     * @return 结果
     */
    @Override
    public int deleteHouseByHouseId(String houseId) {
        return houseMapper.deleteHouseByHouseId(houseId);
    }

    @Override
    public int softDeleteHouseByHouseId(String houseId, String tenantId) {
        House houseByHouseId = houseMapper.selectHouseByHouseId(houseId);
        if (!StrUtil.equals(houseByHouseId.getTenantId(), tenantId)) {
            throw new ServiceException("不能操作其他机构的房屋");
        }
        return houseMapper.softDeleteHouseByHouseId(houseId);
    }

    @Override
    public int editState(String houseId, String tenantId) {
        House house = houseMapper.selectHouseByHouseId(houseId);
        if (ObjectUtil.isEmpty(house)) {
            throw new ServiceException("房源不存在");
        }
        if (!StrUtil.equals(house.getTenantId(), tenantId)) {
            throw new ServiceException("不能操作其他机构的房屋");
        }
        if (StrUtil.equals(house.getHouseState(), HouseConstants.HOUSE_STATE_UP)) {
            house.setHouseState(HouseConstants.HOUSE_STATE_DOWN);
        } else if (StrUtil.equals(house.getHouseState(), HouseConstants.HOUSE_STATE_DOWN)) {
            house.setHouseState(HouseConstants.HOUSE_STATE_UP);
        }
        return houseMapper.updateHouseState(house);
    }

    @Override
    public House flatSelectHouseByHouseId(String houseId) {
        House house = houseMapper.selectHouseByHouseId(houseId);
        if (ObjectUtil.isNotEmpty(house)) {
            if (StrUtil.isNotBlank(house.getLabelIds())) {
                List<Long> labelIds = StrUtil.splitTrim(house.getLabelIds(), ',').stream().map(Long::parseLong).collect(Collectors.toList());
                List<HouseLabel> labelList = houseLabelService.selectHouseLabelByLabelIds(labelIds);
                house.setHouseLabelList(labelList);
            }
            if (StrUtil.isNotBlank(house.getFacilitiesIds())) {
                List<Long> facilitiesIds = StrUtil.splitTrim(house.getFacilitiesIds(), ',').stream().map(Long::parseLong).collect(Collectors.toList());
                List<HouseFacilities> facilitiesList = houseFacilitiesService.selectHouseFacilitiesByFacilitiesIds(facilitiesIds);
                house.setHouseFacilityList(facilitiesList);
            }
        }
        return house;
    }

    @Override
    public List<House> flatSelectHouseList(House house) {
        List<House> houseList = houseMapper.selectHouseList(house);
        if (CollectionUtil.isNotEmpty(houseList)) {
            // 提取所有House的labelIds并去重
            Set<Long> allLabelIds = houseList.stream()
                    .map(House::getLabelIds)
                    .filter(Objects::nonNull)
                    .flatMap(labelIds -> StrUtil.splitTrim(labelIds, ',').stream())
                    .map(Long::parseLong)
                    .collect(Collectors.toSet());

            if (allLabelIds.isEmpty()) {
                return houseList;
            }

            // 批量查询所有标签
            Map<Long, HouseLabel> labelMap = houseLabelService.selectHouseLabelByLabelIds(new ArrayList<>(allLabelIds))
                    .stream()
                    .collect(Collectors.toMap(HouseLabel::getLabelId, label -> label));

            // 关联标签到House对象
            houseList.forEach(h -> {
                if (h.getLabelIds() != null) {
                    List<HouseLabel> labels = StrUtil.splitTrim(h.getLabelIds(), ',')
                            .stream()
                            .map(Long::parseLong)
                            .map(labelMap::get)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    h.setHouseLabelList(labels);
                }
            });
        }

        return houseList;
    }

    @Override
    public List<House> flatSelectHouseListByUser(House house) {
        return houseMapper.flatSelectHouseListByUser(house);
    }

    @Override
    public HomePageVO homePage(String tenantId) {
        HomePageVO homePageVO = new HomePageVO();
        //统计账单未付款、逾期数量
        List<Map<String, Object>> billMapList = billService.homePage(tenantId);
        Map<String, Object> billMap = new HashMap<>();
        for (Map<String, Object> map : billMapList) {
            String key = (Long) map.get("type") == 1 ? "unPaid" : "overdue";
            billMap.put(key, map.get("num"));
        }
        homePageVO.setBillMap(billMap);

        //统计空置数量、全部房屋数量
        List<Map<String, Object>> houseMapList = houseMapper.homePage(tenantId);
        Map<String, Object> houseMap = new HashMap<>();
        for (Map<String, Object> map : houseMapList) {
            String key = (Long) map.get("type") == 1 ? "vacancy" : "all";
            houseMap.put(key, map.get("num"));
        }
        homePageVO.setHouseMap(houseMap);

        //统计报修待处理
        int waiting = repairsService.countWaiting(tenantId);
        homePageVO.setRepairsWaiting(waiting);

        //统计租客池总数
        int total = houseLeadService.countTotal(tenantId);
        homePageVO.setHouseLeadTotal(total);

        return homePageVO;
    }

    @Override
    public Map homePageDeviceLock(String tenantId) {
        List<String> macList = deviceLockService.selectDeviceLockMacList(tenantId);
        Map result = new HashMap<>();
        if (CollectionUtil.isNotEmpty(macList)) {
            JSONObject jsonObject = lockDevicesService.homePage(macList);
            result = JSONObject.parseObject(jsonObject.getString("data"), Map.class);
        }
        result.put("total", macList.size());
        return result;
    }

    @Override
    public AjaxResult importHouse(List<House> houseList, String userName, String tenantId) {
        Date nowDate = DateUtils.getNowDate();
        List<House> importList = new ArrayList<>();
        for (House house : houseList) {
            if (ObjectUtil.isNotEmpty(house.getRent())) {
                int rent = house.getRent().compareTo(BigDecimal.ZERO);
                if (rent <= 0) {
                    continue;
                }
                if (house.getRent().scale() > 2) {
                    continue;
                }
                if (StrUtil.isEmpty(house.getRentUnit())) {
                    continue;
                }
            }
            if (house.getFloor() > house.getTotalFloor()) {
                continue;
            }
            String houseId = "H" + System.currentTimeMillis() + RandomUtils.nextInt(10000, 100000);
            house.setHouseId(houseId);
            house.setCreateBy(userName);
            house.setCreateTime(nowDate);
            house.setTenantId(tenantId);
            importList.add(house);
        }
        if (CollectionUtil.isNotEmpty(importList)) {
            int result = houseMapper.insertBatchHouse(importList);
            String successMsg = "成功导入" + result + "条房源";
            return AjaxResult.success(successMsg);
        }
        return AjaxResult.error("导入失败");
    }

    public AjaxResult checkParams(House house) {
        if (ObjectUtil.isNotEmpty(house.getRent())) {
            int rent = house.getRent().compareTo(BigDecimal.ZERO);
            if (rent <= 0) {
                return AjaxResult.warn("租金只能大于0");
            }
            if (house.getRent().scale() > 2) {
                return AjaxResult.warn("租金小数点最多两位小数");
            }
            if (StrUtil.isEmpty(house.getRentUnit())) {
                return AjaxResult.warn("租金单位不能为空");
            }
        }
        if (CollectionUtil.isEmpty(house.getHousePictureList())
                || house.getHousePictureList().size() > 9) {
            return AjaxResult.warn("房屋图片最多9张");
        }
        if (house.getFloor() > house.getTotalFloor()) {
            return AjaxResult.warn("楼层不能大于总楼层");
        }
        return null;
    }
}
